/*
 * Copyright (c) 2014, Asiainfo-Linkage. All rights reserved.
 * Asiainfo-Linkage PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package edu.w106.platform.http;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.HttpGet;

import com.alibaba.fastjson.JSON;

import edu.w106.platform.utils.MD5;

/**
 * <p><b>标题：</b>HttpGetUtils.</p>
 *
 * <p><b>描述：</b></p>
 *
 * <p><b>版权：</b>Copyright (c) 2014 亚信联创</p>
 *
 * <p><b>工程：</b>w106-mc</p>
 *
 * @author w106
 *
 * @version 1.0.0
 *
 * @since 2014-5-4 下午4:57:36
 */
public class HttpGetUtils extends HttpClientUtils {

    /**
     * 
     */
    private static final String HTTP_HEAD_ETAG = "ETag";

    /**
     * 
     */
    private static final String HTTP_HEAD_LAST_MODIFIED = "Last-Modified";

    private Response cacheReponse = null;

    private final String tempDir = "work";

    public HttpGetUtils() {
        //        tempDir = System.getProperty("java.io.tmpdir");
    }

    /**
     * 如果是get请求，采用缓存的方式进行.
     * @param uri
     * @return
     */
    public Response sendRequest(String uri) {
        try {

            HttpGet httpGet = new HttpGet(uri);
            cacheReponse = readFromDisk(uri);
            if (cacheReponse != null) {
                addModifiedSince(httpGet, cacheReponse);
            }
            Response newResponse = sendRequest(httpGet);
            if (newResponse.getStatus() == 200) {
                if (modified(cacheReponse, newResponse)) {
                    cache2Disk(cacheReponse, newResponse);
                } else {
                    newResponse.setStatus(304);
                }

            }
            if (newResponse.getStatus() == 304) {
                newResponse.setResponse(cacheReponse.getResponse());
            }
            return newResponse;
        } catch (Exception e) {
            Response resp = new Response(uri);
            resp.setResponse(e.getMessage());
            return resp;
        }
    }

    /**
     * 页面是否更新.
     * @param disk
     * @param page
     * @return true:页面修改 false：页面未修改.
     */
    private boolean modified(Response cache, Response page) {
        if (cache == null) {
            return true;
        }
        List<String> diskLast = cache.getHead(HTTP_HEAD_LAST_MODIFIED);
        List<String> diskLastetag = cache.getHead(HTTP_HEAD_ETAG);
        if (diskLast.isEmpty() || diskLastetag.isEmpty()) {
            return true;
        }
        List<String> pageLast = page.getHead(HTTP_HEAD_LAST_MODIFIED);
        List<String> pageLastetag = page.getHead(HTTP_HEAD_ETAG);
        if (pageLast.isEmpty() || pageLastetag.isEmpty()) {
            return true;
        }
        //本地缓存的页面和请求的页面头信息相同.
        if (diskLast.get(0).equals(pageLast.get(0)) && diskLastetag.get(0).equals(pageLastetag.get(0))) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 缓存到本地.
     * @param resp
     */
    private void cache2Disk(Response diskcache, Response resp) {

        String json = JSON.toJSONString(resp);
        try {
            FileUtils.writeStringToFile(getCacheFile(resp.getUrl()), json);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private File getCacheFile(String url) {
        return new File(tempDir, MD5.encrypt(url) + ".json");
    }

    /**
     * 添加http头
     * @param httpPost
     */
    private void addModifiedSince(HttpGet httpPost, Response diskcache) {
        List<String> ims = diskcache.getHead(HTTP_HEAD_LAST_MODIFIED);
        if (!ims.isEmpty()) {
            httpPost.addHeader("If-Modified-Since", ims.get(0));
        }
        List<String> etag = diskcache.getHead(HTTP_HEAD_ETAG);
        if (!etag.isEmpty()) {
            httpPost.addHeader("If-None-Match", etag.get(0));
        }
    }

    private Response readFromDisk(String url) {
        File cache = getCacheFile(url);
        if (!cache.exists()) {
            return null;
        }
        try {
            String cachestr = FileUtils.readFileToString(cache);
            Response resp = JSON.parseObject(cachestr, Response.class);
            return resp;
        } catch (IOException ex) {
            cache.delete();
            return null;
        }

    }

    public Response getCacheReponse() {
        return cacheReponse;
    }
}
